package com.tanhua.server.service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tanhua.autoconfig.template.FaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.dubbo.api.mongo.VisitorApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.*;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.joda.time.DateTime;
import org.joda.time.Years;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户注册-完善个人（保存用户信息、上传头像）-业务实现类
 */
@Service
@Slf4j
public class UserInfoService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private FaceTemplate faceTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private VisitorApi visitorApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    /**
     * 第二步：用户注册：保存用户信息
     *
     * @param userInfoVo
     */
    public void loginReginfo(UserInfoVo userInfoVo) {
        //3.如果登录，则调用服务提供者 保存用户信息
        UserInfo userInfo = new UserInfo();
        //将相同属性 相同类型 的数据从一个对象 copy 另一个对象中
        BeanUtils.copyProperties(userInfoVo, userInfo);
        userInfo.setId(UserHolder.getUserId()); //当前登录用户id 跟 tb_userInfo表 一对一
        userInfo.setAge(getAge(userInfoVo.getBirthday()));//设置年龄
        userInfoApi.add(userInfo);
    }

    /**
     * 根据请求头中token获取user对象
     * @param token
     * @return
     */
    /*private User getLoginUserByToken(String token) {
        String tokenKey = "TOKEN_" + token;
        String userStr = stringRedisTemplate.opsForValue().get(tokenKey);
        //2.如果没有登录 抛出异常
        if(StringUtils.isEmpty(userStr)){
            throw new TanHuaException(ErrorResult.loginFail());
        }
        //2.1 根据userStr 转user对象 并获取用户id
        return JSON.parseObject(userStr, User.class);
    }*/


    /**
     * 通过年-月-日获取年龄
     *
     * @param yearMonthDay
     * @return
     */
    private int getAge(String yearMonthDay) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date birthDay = sdf.parse(yearMonthDay);
            Years years = Years.yearsBetween(new DateTime(birthDay), DateTime.now());
            return years.getYears();
        } catch (ParseException e) {
            log.error("获取用户年龄失败!", e);
            return 0;
        }
    }

    /**
     * 第三步：用户注册：上传头像
     */
    public void loginHeadReginfo(MultipartFile headPhoto) {
        try {
            //2.调用百度人脸识别
            boolean faceFlag = faceTemplate.detect(headPhoto.getBytes());
            if (!faceFlag) {
                throw new TanHuaException(ErrorResult.faceError());
            }
            //3.调用阿里云oss
            String filename = headPhoto.getOriginalFilename();//原始文件名称
            String headUrl = ossTemplate.upload(filename, headPhoto.getInputStream()); //调用阿里云服务 返回头像地址
            //4.调用服务提供者 更新头像地址
            UserInfo userInfo = new UserInfo();
            userInfo.setId(UserHolder.getUserId());//当前用户id
            userInfo.setAvatar(headUrl);//头像地址
            userInfoApi.update(userInfo);
        } catch (IOException e) {
            e.printStackTrace();
            throw new TanHuaException(ErrorResult.error());
        }
    }

    /**
     * 用户信息管理-查询用户资料
     */
    public UserInfoVo getUserInfo(Long userID) {
        //1.获取userId
        Long userId = UserHolder.getUserId();
        //2.调用服务提供者 查询用户资料
        if (userID != null) {
            userId = userID;
        }
        UserInfo userInfo = userInfoApi.getUserInfo(userId);
        //3.构造UserInfoVo返回
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        userInfoVo.setId(userId);//设置用户id
        return userInfoVo;
    }

    /**
     * 用户信息管理-更新用户资料
     */
    public void updateUserInfo(UserInfoVo userInfoVo) {
        //2.调用服务提供者 更新用户资料
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoVo, userInfo);
        userInfo.setId(UserHolder.getUserId());//设置当前用户id 需要根据id更新用户信息
        userInfo.setAge(getAge(userInfoVo.getBirthday()));
        userInfoApi.update(userInfo);
    }


    /**
     * 我喜欢的
     *
     * @param page
     * @param pageSize
     * @param nickName
     * @return
     */
    public PageResult<FriendsVo> findMyLove(Long page, Long pageSize, String nickName) {
        //1 根据当前用户id与分页参数调用服务分页查询好友列表数据
        PageResult<UserLike> userLikesResult = userLikeApi.findMyLove(page, pageSize, UserHolder.getUserId());
        if (userLikesResult == null || CollectionUtils.isEmpty(userLikesResult.getItems())) {
            return new PageResult<>(0L, 10L, 0L, 1L, null);
        }
        //2 获取所有喜欢的用户id
        List<UserLike> userLikeList = userLikesResult.getItems();
        List<Long> userLikeIds = userLikeList.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        //3.根据所有喜欢的用户id以及nickname关键字获取所有好友详情数据
        UserInfo uc = new UserInfo();
        uc.setNickname(nickName);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userLikeIds, uc);
        //4.基于喜欢的用户详情数据 构造 Vo返回
        List<FriendsVo> flipListVoList = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            UserInfo userInfo = userInfoMap.get(userLike.getLikeUserId());//获取喜欢的用户详情
            if (userInfo != null) {
                FriendsVo vo = new FriendsVo();
                BeanUtils.copyProperties(userInfo, vo);
                vo.setMatchRate(88);
                vo.setAlreadyLove(userLike.getIsLike());
                flipListVoList.add(vo);
            }
        }
        return new PageResult<>(page, (long) userLikeList.size(), userLikesResult.getCounts(), flipListVoList);
    }

    /**
     * 分页查询相互喜欢列表
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult<FriendsVo> eachLove(Long page, Long pageSize, String nickname) {
        //1 根据当前用户id与分页参数调用服务分页查询好友列表数据
        PageResult<UserLike> userLikesResult = userLikeApi.eachLove(page,pageSize,UserHolder.getUserId());
        if (userLikesResult == null || org.springframework.util.CollectionUtils.isEmpty(userLikesResult.getItems())) {
            return new PageResult<>(0l, 10l, 0l, 1l, null);
        }
        //2 获取所有喜欢的用户id
        List<UserLike> userLikeList = userLikesResult.getItems();
        List<Long> userIds = userLikeList.stream().map(UserLike::getUserId).collect(Collectors.toList());
        //3.根据所有喜欢的用户id以及nickname关键字获取所有好友详情数据
        UserInfo uc = new UserInfo();
        uc.setNickname(nickname);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, uc);
        //4.基于喜欢的用户详情数据 构造 Vo返回
        List<FriendsVo> friendsVoList = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            UserInfo userInfo = userInfoMap.get(userLike.getUserId());//获取喜欢的用户详情
            if (userInfo != null){
                FriendsVo vo = new FriendsVo();
                BeanUtils.copyProperties(userInfo,vo);
                vo.setMatchRate(88);
                vo.setAlreadyLove(userLike.getIsLike());
                friendsVoList.add(vo);
            }
        }
        return new PageResult<>(page,(long) userLikeList.size(),userLikesResult.getCounts(),friendsVoList );
    }


    /**
     * 喜欢取消
     */
    public void deleteLove(Long uid) {
        Long userId = UserHolder.getUserId();
        userLikeApi.deleteLove(userId,uid);
    }


    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     */

    public CountsVo counts() {

        //获取用户id
        Long userId = UserHolder.getUserId();


        //根据用户id查询好友表获取总数量
        Integer friendCount=userLikeApi.countById(userId);


        //根据用户id查询user_like表 根据islike判断是否喜欢获取喜欢的总数量
        Integer like=  userLikeApi.findByUserId(userId);
        Integer likeMe=  userLikeApi.findByLikeUserId(userId);

        CountsVo countsVo = new CountsVo();

        countsVo.setLoveCount(like);
        countsVo.setFanCount(likeMe);
        countsVo.setEachLoveCount(friendCount);

        return countsVo;
    }

    /**
     * 谁看过我分页列表
     * @param page
     * @param pageSize
     * @param nickname
     * @return
     */
    public PageResult<FriendsVo> visitorsMe(Long page, Long pageSize, String nickname) {
        //1 根据当前用户id与分页参数调用服务分页查询访客列表数据
        PageResult<Visitors> visitorsMeResult = visitorApi.visitorsMe(page,pageSize,UserHolder.getUserId());
        if (visitorsMeResult == null || CollectionUtils.isEmpty(visitorsMeResult.getItems())) {
            return new PageResult<>(0l, 10l, 0l, 1l, null);
        }
        //2 获取所有访客的用户id
        List<Visitors> visitorsMeList = visitorsMeResult.getItems();
        List<Long> visitorsIds = visitorsMeList.stream().map(Visitors::getVisitorUserId).collect(Collectors.toList());
        //3.根据所有访客的用户id以及nickname关键字获取所有好友详情数据
        UserInfo uc = new UserInfo();
        uc.setNickname(nickname);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(visitorsIds, uc);
        //4.基于访客的用户详情数据 构造 Vo返回
        List<UserLike> userLikesList = new ArrayList<>();
        List<FriendsVo> vo = new ArrayList<>();
//        List<UserInfo> userInfoList = userInfoMap.values().stream().collect(Collectors.toList());
        for (Visitors visitors : visitorsMeList) {

            UserInfo userInfo = userInfoMap.get(visitors.getVisitorUserId());//获取访客的用户详情
            if (userInfo != null){
                FriendsVo friendsVo = new FriendsVo();
                BeanUtils.copyProperties(userInfo,friendsVo);
                friendsVo.setMatchRate(88);
                userLikesList = userLikeApi.findByIdss(UserHolder.getUserId(),visitorsIds);
                if (CollectionUtils.isNotEmpty(userLikesList)) {
                    for (UserLike userLike : userLikesList) {
                        friendsVo.setAlreadyLove(userLike.getIsLike());

                    }

                }
                vo.add(friendsVo);

            }
        }
        return new PageResult<>(page,pageSize,visitorsMeResult.getCounts(),vo);
    }


    /**
     * 粉丝分页列表查询
     */
    public PageResult<FriendsVo> fansListPage(Long page, Long pageSize, String nickName) {
        //1.调用服务，查询粉丝表UserLike分页列表数据
        PageResult<UserLike> userLikePageResult = userLikeApi.fansListPage(page, pageSize, UserHolder.getUserId());
        if (userLikePageResult == null || CollectionUtils.isEmpty(userLikePageResult.getItems())) {
            return new PageResult<>(0l, 10l, 0l, 1l, null);
        }
        Long counts = userLikePageResult.getCounts();//获取userLike粉丝数量
        //2.获取粉丝ids
        List<UserLike> UserLikeItems = userLikePageResult.getItems();
        List<Long> listLikeUserIds = UserLikeItems.stream().map(UserLike::getUserId).collect(Collectors.toList());
        //3.根据粉丝ids以及keyword关键字获取所有粉丝详情数据
        UserInfo uc = new UserInfo();
        uc.setNickname(nickName);//昵称
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(listLikeUserIds, uc);

        //4.基于粉丝详情数据 构造 UserLikeVo返回
        List<FriendsVo> userLikeVoList = new ArrayList<>();
        for (UserLike userLike : UserLikeItems) {
            //获取粉丝用户详情
            UserInfo userInfo = userInfoMap.get(userLike.getUserId());
            if (null != userInfo) {
                //创建userLikeVo对象
                FriendsVo userLikeVo = new FriendsVo();
                //userLike拷贝到UserLikeVo
                BeanUtils.copyProperties(userInfo, userLikeVo);

                userLikeVo.setMatchRate(88);
                userLikeVo.setAlreadyLove(userLike.getIsLike());
                userLikeVoList.add(userLikeVo);
            }
        }
        return new PageResult<FriendsVo>(page, pageSize, counts, userLikeVoList);
    }

    /**
     * 粉丝 喜欢
     */
    public void loveFansList(Long likeUserId) {
        //调用服务
        userLikeApi.loveFansList(likeUserId, UserHolder.getUserId());
    }








}
